package uYach

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

var (
	yachBaseUrl = "https://yach-oapi.zhiyinlou.com/robot/send"
)

type Yach struct {
	Token  string
	Secret string
}

func NewYach(token string, secret string) *Yach {
	yach := new(Yach)
	yach.Token = token
	yach.Secret = secret

	return yach
}

// ComputeHmacSha256 sha256+base64
func ComputeHmacSha256(message string, secret string) string {
	h := hmac.New(sha256.New, []byte(secret))
	h.Write([]byte(message))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

// Robot send robot msg
func (this *Yach) Send(msg *Msg) error {

	// 生成签名
	timestamp := time.Now().Unix() * 1000
	message := fmt.Sprintf("%d\n%s", timestamp, this.Secret)
	sign := ComputeHmacSha256(message, this.Secret)

	URL := fmt.Sprintf("%s?access_token=%s&timestamp=%d&sign=%s", yachBaseUrl, this.Token, timestamp, url.QueryEscape(sign))

	msgBody, err := msg.Encode()
	if err != nil {
		return err
	}

	fmt.Println(string(msgBody))

	// 准备请求数据
	req, _ := http.NewRequest("POST", URL, bytes.NewReader(msgBody))
	req.Header.Set("Content-Type", "application/json")

	httpClient := &http.Client{
		Timeout: 3 * time.Second,
	}
	resp, errDo := httpClient.Do(req)
	if errDo != nil {
		return errDo
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return fmt.Errorf("Net request failed, response status: %s, url: %s, req: %s", resp.Status, URL, string(msgBody))
	}

	return nil
}